package com.ctg.itrdc.sysmgr.permission.core.filter;

import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ctg.itrdc.sysmgr.permission.core.utils.WebUtils;

public class ExFormAuthenticationFilter extends FormAuthenticationFilter {
	
	private static final Logger log = LoggerFactory.getLogger(ExFormAuthenticationFilter.class);

	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }
                return executeLogin(request, response);
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Login page view.");
                }
                //allow them to see the login page ;)
                return true;
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Attempting to access a path which requires authentication.  Forwarding to the " +
                        "Authentication url [" + getLoginUrl() + "]");
            }
            
            if(request instanceof HttpServletRequest) {
            	HttpServletRequest httpRequest = (HttpServletRequest)request;
            	if(WebUtils.isAjax(httpRequest)) {
            		saveRequest(request);
            		HttpServletResponse res = (HttpServletResponse)response;
            		PrintWriter out = res.getWriter();
                    out.print("{\"resultCode\":\"200\",\"redirect\":\"true\",\"resultMsg\":\""+ getLoginUrl() + "\"}");
                    out.close();
            		return false;
            	}
            }
            
            saveRequestAndRedirectToLogin(request, response);
            return false;
        }
    }
	
}
